package com.broada.apm.indicator.api.impl;

import java.util.List;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broada.apm.es.indices.support.PerfIndicesBuilder;
import com.broada.apm.indicator.api.TransactionRecordService;
import com.broada.apm.model.Scope;
import com.broada.apm.model.TransactionRecord;
import com.broada.apm.utils.EsClientUtil;
import com.broada.apm.utils.ExceptionUtils;
import com.broada.apm.utils.JsonUtil;

public class TransactionRecordServiceImpl implements TransactionRecordService {
	
	private static final Logger LOG = LoggerFactory.getLogger(TransactionRecordServiceImpl.class);
	private Client client = EsClientUtil.getTransportClient();

	@Override
	public void recordTransactions(List<TransactionRecord> recordList) {
		try {
            PerfIndicesBuilder perfIncidesBuilder = PerfIndicesBuilder.getInstance();
            BulkRequestBuilder bulkbuilder = client.prepareBulk();
            for (TransactionRecord tr : recordList) {
                for (String index : perfIncidesBuilder.getTransactionIndices(tr)) {
                    bulkbuilder.add(client.prepareIndex(index, Scope.APMRUNNING_TRANS.getType(), tr.getId())
                            .setSource(JsonUtil.obj2json(tr)));
                }
            }
            BulkResponse bulkResponse = bulkbuilder.execute().actionGet();
            if (bulkResponse.hasFailures()) {
                ExceptionUtils.error(LOG, String.format("交易明细信息组保存失败:%s", bulkResponse.buildFailureMessage()),
                        new Exception());
            }
        } catch (Exception e) {
            ExceptionUtils.error(LOG, String.format("交易明细信息组保存失败:%s", e), e);
        }
	}

	@Override
	public void recordTransactionDetails(List<com.broada.apm.model.TransactionDetail> detailList) {
		try {
			PerfIndicesBuilder perfIndicesBuilder = PerfIndicesBuilder.getInstance();
			BulkRequestBuilder bulkRequest = client.prepareBulk();
			for (com.broada.apm.model.TransactionDetail td : detailList) {
				for (String index : perfIndicesBuilder.getTransactionDetailIndices(td)) {
					bulkRequest.add(client.prepareIndex(index, Scope.APMRUNNING_TRANSDETAIL.getType(), td.getId())
			                .setSource(JsonUtil.obj2json(td)));
			    }
			}
			BulkResponse bulkResponse = bulkRequest.execute().actionGet();
            if (bulkResponse.hasFailures()) {
                ExceptionUtils.error(LOG, String.format("交易原始信息组保存失败:%s", bulkResponse.buildFailureMessage()),
                        new Exception());
            }
		} catch (Exception e) {
			ExceptionUtils.error(LOG, String.format("交易原始信息组保存失败:%s", e), e);
		}
	}

}
